package com.ttmusic.utils.baidu;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 请求参数
 * @author Administrator
 *
 */
public class HttpParams {
	
    Map<String, String> params = new HashMap<String, String>();

    Class<?> bases[] = {Integer.class, Long.class, Short.class, Float.class, Double.class, String.class};

    public void add(String key,Object param) {
        try {
            if(isValidate(param)){
                params.put(key,param +"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, String> getParams() {
        return params;
    }
    
    /**
     * 获取查询字符串 参数名=参数值&参数名=参数值 格式
     * @return
     */
    public String getQueryString() {
    	StringBuilder queryString = new StringBuilder();
    	for(Entry<String, String> en : params.entrySet()) {
    		queryString.append(en.getKey() + "=" + en.getValue() + "&");
    	}
    	String str = queryString.toString();
    	if(str.endsWith("&"))
    		str = str.substring(0, str.length()-1);
    	return str;
    }

    /**
     * 验证参数值的类型是否有效
     * @param param
     * @return
     * @throws Exception
     */
    public boolean isValidate(Object param) throws Exception{
        for (Class<?> c : bases) {
            if(param.getClass() == c)
                return true;
        }
        throw new Exception("param "+param+" is not allowed.");
    }
}
